package com.geeke.sys.service;

import java.util.List;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.CrudService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;

import com.geeke.sys.dao.CodeRuleDao;
import com.geeke.sys.entity.CodeRule;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;

/**
 * 系统编号规则 Service
 * @author
 * @version
 */

@Service("codeRuleService")
@Transactional(readOnly = true)
public class CodeRuleService extends CrudService<CodeRuleDao, CodeRule> {

    @Override
    public CodeRule get(String id) {
        CodeRule codeRule = super.get(id);
        return codeRule;
    }

    @Transactional(readOnly = false)
    @Override
    public CodeRule save(CodeRule codeRule) {
        // 重复性检查
        List<Parameter> params = Lists.newArrayList();
        
        // 编号重复性检查
        params.clear();
        params.add(new Parameter("codeRule.code", "=", codeRule.getCode()));
        params.add(new Parameter("codeRule.del_flag", "=", codeRule.getDelFlag()));

        if(!StringUtils.isBlank(codeRule.getId())) {
          params.add(new Parameter("codeRule.id", "<>", codeRule.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同编号"));
        }

        CodeRule codeRuleTemp = super.save(codeRule);
        return codeRuleTemp;
    }

    public List<CodeRule> listNotInCompany(String companyId) {
        return dao.listNotInCompany(companyId);
    }

    @Cacheable(value = "codeRule", key = "#code")
    public String getRuleDefByCode(String code) {
        return dao.getRuleDefByCode(code);
    }

    // 根据明确需求实现的其他方法
} 